//
//  TFVoteSelectView.swift
//  TalkfunSDKDemo
//
//  Created by 邓盛明 on 2022/2/18.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit


class TFVoteSelectView: UIScrollView,UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //图形模式
        if ((self.result != nil)&&(self.result.info.imageUrl.count) > 0) {
               
               if (section == 0) {
                   return 1;
               }else{
                   return self.dataSource.count;
               }
           }

       return self.dataSource.count;
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        //图形模式
        if ((self.result != nil)&&(self.result.info.imageUrl.count) > 0) {
              
              return 2;
          }
          
          return 1;
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if self.headView == nil {
            
     

            let v = UIView.init()
            let lab = UILabel.init()
            
            lab.numberOfLines = 0;
            self.headLab = lab;
            lab.font = UIFont.systemFont(ofSize: 16)
            lab.textColor = UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1.0)
           
            self.headView = v;
        }

       let rect = self.getheaderRect()
       self.headLab.frame = CGRect(x: 12, y: 10, width: self.frame.size.width-32, height: rect.size.height)
     
      self.headView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: rect.size.height+20)
        self.headView.addSubview(self.headLab)
        return self.headView;
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        //防止result 为空
        if self.result == nil {
            return 0
        }
        
        
        if ((self.result.info.imageUrl.count) > 0) {
            if (section==0) {
                return 0;
            } else {
                let rect = self.getheaderRect()
                return rect.size.height+20;
            }
        } else {
            
            let rect = self.getheaderRect()
            return rect.size.height+20;
            
        }
       
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (self.result == nil) {
            return 0;
        }
        if (indexPath.section == 0 && (self.result.info.imageUrl.count) > 0) {
            return  self.frame.size.width *  (9.0/16.0);
        }
        let op = self.result.opList[indexPath.row] as! TFOp
        let opstr = "\(TalkfunSharedTools.asciiBytesToString(inx: indexPath.row))" + "." + "\(op.op)"
        var t:CGFloat = 31;
        if self.result.info.endTime != "0" {
            t = 17+91;
        }
        
        let rect = TalkfunSharedTools.getRectWith(opstr, size: CGSize(width: self.tableview.frame.size.width-48-t, height: CGFloat(MAXFLOAT)), fontSize: 16)
          
            return rect.size.height+20+16;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        if (indexPath.section == 0  && self.result != nil && (self.result.info.imageUrl.count) > 0) {
            let cell = tableview.dequeueReusableCell(withIdentifier: "selectImgCell") as! TFVoteSelectImgviewCell
            cell.selectionStyle = .none
            let url:URL? = URL.init(string: self.result.info.imageUrl)
            self.imgView.sd_setImage(with: url, completed: nil)
            cell.cellWidth = self.frame.size.width;
     
            return cell;
        } else {
            let cell = tableview.dequeueReusableCell(withIdentifier: "selectCell") as! TFVoteSelectCell
           
            cell.cellwidth = self.frame.size.width;
          
            cell.selectionStyle = .none;
            if self.result != nil {
                cell.cellConfig(self.result, indexpath: indexPath as NSIndexPath)
            }
            
         
            return cell;
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.result == nil {
            return;
        }
        if (indexPath.section == 0  &&   (self.result.info.imageUrl.count) > 0) {
            let keyWindow = TalkfunSharedTools.keyWindow()
         
                self.imageUrlView = TF_BackImagePreviewView.init()
                keyWindow.addSubview(self.imageUrlView)
                
                   
                self.imageUrlView.frame = TalkfunSharedTools.getMainScreen()
                self.imageUrlView.layoutSubviewsUI(imageUrl: self.result.info.imageUrl)
            
            
          
           
            return;
        }
        
        let model = self.result.opList[indexPath.row] as! TFOp
        if (self.result.optional == 1) {

            for i in 0..<self.result.opList.count {
                let op = self.result.opList[i] as! TFOp
                op.selected = false
            }
          

            model.selected = true;
            self.submit.isUserInteractionEnabled = true;
            self.submit.setTitleColor(UIColor.white, for: .normal)
            self.submit.backgroundColor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)

        } else {
            var count = 0;
            for i in 0..<self.result.opList.count {
                let op = self.result.opList[i] as! TFOp
                if op.selected == true {
                    count = count + 1
                }
               
            }
           
     
            if (self.result.optional > 1 ) {
                model.selected = !model.selected;

            }
      

            count = 0;
            for i in 0..<self.result.opList.count {
                let op = self.result.opList[i] as! TFOp
                if op.selected == true {
                    count = count + 1
                }
               
            }
           
            //判断是否是多选           判断选 了几个
            if (count > 0) {
                
                self.submit.isUserInteractionEnabled = true;
                self.submit.setTitleColor(UIColor.white, for: .normal)
        
                self.submit.backgroundColor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)
            }

            else{
                //默认颜色
             self.submit.isUserInteractionEnabled = false;
             
                self.backButtonClickUI()
            }

        }
        
        self.tableview.reloadData()
    }
    
    //投票成功
    @objc public var voteSuccessfulHidde:UIButton!
    @objc public var submit:UIButton! //提交投票
    @objc public var closeBtn:UIButton!
    @objc public var backBtn:UIButton!
    @objc public var result:TFVoteData!
    @objc public var dataSource:NSMutableArray = NSMutableArray.init()
    @objc public var detailView:UIView!
    @objc public var isShow: Bool = false //出现为yes,隐藏为NO;

    //你的选项：B
    var optionPrompt:UILabel!
    var imgView:UIImageView!//老师头像
    var titleLab:UILabel!
    var tableview:UITableView!
    var indexPathRow:Int = 0
    var headView:UIView!
    var headLab:UILabel!
    var scrollLineView:UIView!
    var imageUrlView:TF_BackImagePreviewView!
   
    var rect:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.showsVerticalScrollIndicator = false;
        self.showsHorizontalScrollIndicator = false;
        
        self.isScrollEnabled = false;
        self.isPagingEnabled = true;
        
        //投票详情
        self.detailView = UIView.init()
        addSubview(self.detailView)
        self.detailView.backgroundColor = UIColor.white
 
        self.voteSuccessfulHidde = UIButton.init()
        self.voteSuccessfulHidde.backgroundColor = UIColor.clear
        addSubview(self.voteSuccessfulHidde)

        self.imgView = UIImageView.init()
        self.imgView.image = UIImage.init(named: "HTLive.bundle/head photo")
        self.detailView.addSubview(self.imgView)
    
        
        self.titleLab = UILabel.init()
        self.titleLab.text = "老师发起一个投票";
        self.titleLab.textColor = UIColor(red: 153/255.0, green: 153/255.0, blue: 153/255.0, alpha: 1.0)
        self.titleLab.font = UIFont.PingFang(size: 14)
        self.detailView.addSubview(self.titleLab)
        
        
        self.closeBtn = UIButton.init()
        self.closeBtn.setImage(UIImage.init(named: "HTLive.bundle/close_gray"), for: .normal)
        self.detailView.addSubview(self.closeBtn)
        
        self.backBtn = UIButton.init()
        self.backBtn.setImage(UIImage.init(named: "HTLive.bundle/TF_vote_back"), for: .normal)
        self.detailView.addSubview(self.backBtn)

        self.tableview = UITableView.init()
        self.tableview.backgroundColor = UIColor.clear
        self.tableview.separatorStyle = .none;
        self.tableview.delegate = self;
        self.tableview.dataSource = self;
        self.tableview.register(TFVoteSelectCell.self, forCellReuseIdentifier: "selectCell")
        self.tableview.register(TFVoteSelectImgviewCell.self, forCellReuseIdentifier: "selectImgCell")
    
        if #available(iOS 15.0, *) {
            self.tableview.sectionHeaderTopPadding = 0
        }
     
        self.detailView.addSubview(self.tableview)


        self.submit = UIButton.init()
        self.submit.backgroundColor = UIColor(red: 244/255.0, green: 246/255.0, blue: 249/255.0, alpha: 1.0)
        self.submit.setTitleColor(UIColor(red: 150/255.0, green: 160/255.0, blue: 170/255.0, alpha: 1.0), for: .normal)
        self.submit.isUserInteractionEnabled = false
        self.submit.layer.cornerRadius = 4;
        self.submit.layer.masksToBounds = true
        self.submit.setTitle("投票", for: .normal)
        addSubview(self.submit)

        
        self.optionPrompt = UILabel.init()
        self.detailView.addSubview(self.optionPrompt)

        self.optionPrompt.font = UIFont.PingFang(size: 16)
        self.optionPrompt.textColor = UIColor(red: 5/255.0, green: 211/255.0, blue: 128/255.0, alpha: 1.0)
        self.optionPrompt.numberOfLines = 0;

    
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()

        self.contentSize = CGSize(width: self.frame.size.width * 2.0, height: self.frame.size.height)
        self.detailView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        self.imgView.frame = CGRect(x: 16, y: 16, width: 22, height: 22)
      
        self.titleLab.frame = CGRect(x: self.imgView.frame.maxX+8, y: 17, width: self.frame.size.width-80, height: 20)
       
        self.closeBtn.frame = CGRect(x: self.detailView.frame.size.width-10-32, y: 10, width: 32, height: 32)
    
        self.backBtn.frame =  CGRect(x: self.detailView.frame.size.width-10-32-10-32, y: 10, width: 32, height: 32)
       

        self.tableview.frame =  CGRect(x: 0, y: 51, width: self.detailView.frame.size.width, height: self.detailView.frame.size.height-53-123)
      
       
        
        var submitY:CGFloat = 58 - 34;
        if #available(iOS 11.0, *) {
            let keyWindow = TalkfunSharedTools.keyWindow()
            
                if ( keyWindow.safeAreaInsets.bottom) > 0.0 {
                    submitY = 58.0
                }
            
            
        }
     
        self.submit.frame = CGRect(x: (self.frame.size.width - 180)/2, y: self.frame.size.height - 40 - submitY, width: 180, height: 40)
        self.optionPrompt.frame = CGRect(x: 24, y: self.tableview.frame.maxY+17, width: self.frame.size.width - 48, height: 22)
       
    }
    
    
  
    func voteSuccessfulHiddeClick()  {
        UIView.animate(withDuration: 0.25) {
            self.superview?.frame = CGRect(x: 0, y: TalkfunSharedTools.getMainScreen().size.height, width: (self.superview?.frame.size.width)!, height: (self.superview?.frame.size.height)!)
        }
        
    }
    
    @objc public func updataVote(_ result:TFVoteData) {
        self.result = result;
        //已经投票
         
        if result.isShow && result.info.endTime != "0"{  //未结束
            self.submit.isHidden = true;
        } else {
            self.submit.isHidden = false
        }
        self.dataSource.removeAllObjects()
        self.dataSource.addObjects(from: result.opList as! [Any])
  
        self.tableview.tag = 836913;
        
        
        if (result.isShow && result.info.endTime != "0") {
            if ((result.info.answer.count) > 0) {
                self.optionPrompt.isHidden = false;
            } else {
                self.optionPrompt.isHidden = true
            }
           
            var content = "";
           
            for inx in 0..<(self.result.info.answer.count) {
                let s:String = self.result.info.answer[inx] as! String
              
                
                content = content + "\(TalkfunSharedTools.asciiBytesToString(inx:   NSInteger(s)!))"
            }
        
            self.optionPrompt.text = "正确选项:" + "\(content)"
        
        } else {
            self.optionPrompt.isHidden = true;
        }
        
        if (result.info.endTime != "0") {
         
            self.submit.backgroundColor = UIColor(red: 244/255.0, green: 246/255.0, blue: 249/255.0, alpha: 1.0)
           
            self.submit.setTitle("投票已结束", for: .normal)
            self.submit.setTitleColor(UIColor(red: 150/255.0, green: 160/255.0, blue: 170/255.0, alpha: 1.0), for: .normal)
         
        } else {
            if (result.voted) {
              
                self.submit.backgroundColor = UIColor(red: 244/255.0, green: 246/255.0, blue: 249/255.0, alpha: 1.0)
                self.submit.setTitle("已投票", for: .normal)
                self.submit.setTitleColor(UIColor(red: 150/255.0, green: 160/255.0, blue: 170/255.0, alpha: 1.0), for: .normal)
            } else {
                self.submit.setTitle("投票", for: .normal)
                
           
            }
        }


        self.tableview.reloadData()
        self.tableview.flashScrollIndicators()


    }
    //关掉
    @objc public func backButtonClickUI()  {
        
        self.submit.backgroundColor = UIColor(red: 244/255.0, green: 246/255.0, blue: 249/255.0, alpha: 1.0)
        self.submit.setTitleColor(UIColor(red: 150/255.0, green:    160/255.0, blue: 170/255.0, alpha: 1.0), for: .normal)
    
    }
    
    func getheaderRect() -> CGRect {
       var str = "";
        if self.result != nil {
            if (self.result.optional == 1) {
               
                str = "【单选】" + self.result.info.title
            } else {
                str = "【多选】" + self.result.info.title
                
            }
        }
        if self.headLab != nil {
            self.headLab.text = str;
        }
       
        let rect = TalkfunSharedTools.getRectWith(str, size: CGSize(width: self.frame.size.width-32, height: CGFloat(MAXFLOAT)), fontSize: 16)
       
        self.rect = rect;
        return rect;
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let sectionHeaderHeight = self.rect.size.height+20;
        if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {

            scrollView.contentInset = UIEdgeInsets(top: -scrollView.contentOffset.y, left: 0, bottom: 0, right: 0);

        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {

            scrollView.contentInset = UIEdgeInsets(top: -sectionHeaderHeight, left: 0, bottom: 0, right: 0);

        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
